#!/usr/bin/env bash
# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: inkyu

DIFF=false
LAST_COMMIT=false
FILES=()
STYLE="yapf.cfg"
FMT="yapf"
HELP_MSG="Usage: run_fmt (--last-commit|[--vimdiff] FILES..)"

if [[ ${#} -eq 0 ]]; then
  (>&2 echo "${HELP_MSG}")
  exit 1
fi

while [[ ${#} -gt 0 ]]; do
  KEY="${1}"
  case "${KEY}" in
    -d|--diff|--vimdiff)
      DIFF=true
    ;;
    -l|--last-commit)
      LAST_COMMIT=true
    ;;
    -h|--help)
      HELP=true
    ;;
    -*|--*)
      (>&2 echo "Invalid option: ${KEY}")
      HELP=true
    ;;
    *)
      FILES+=("${1}")
    ;;
  esac
  shift
done

if [ "${HELP}" = true ]; then
  (>&2 echo "${HELP_MSG}")
  exit 1
fi

SEARCH_PATH=(base build ml net presto testing thread util)

if [ "${ALL}" = true ]; then
  find ${SEARCH_PATH[*]} \
    -iname "*.py" \
    | xargs -r "${FMT}" --style="${STYLE}" -i
elif [ "${LAST_COMMIT}" = true ]; then
  git diff-tree --no-commit-id --name-only -r HEAD \
    | grep '\.py$' \
    | sed 's/^python\///g' \
    | xargs -r "${FMT}" --style="${STYLE}" -i
else
  if [ "${DIFF}" = true ]; then
    for FILE in "${FILES[@]}"; do
      "${DIFFTOOL}" "${FILE}" <("${FMT}" --style="${STYLE}" "${FILE}")
    done
  else
    "${FMT}" --style="${STYLE}" --recursive -i ${FILES[*]}
  fi
fi
